package b3.widget.home.bottom
{
	import b3.config.*;
	import b3.model.*;
	import b3.net.*;
	import b3.scene.*;
	import b3.scene.build.*;
	import b3.scene.home.*;
	import b3.scene.home.grid.*;
	import b3.util.*;
	import b3.widget.*;
	import b3.widget.basic.*;
	import b3.widget.guide.*;
	import b3.widget.home.unlock.*;
	
	import com.greensock.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.*;
	import flash.text.*;
	import flash.ui.Mouse;

	public class BuildingItem extends Sprite
	{
		private var buildingIndex:int;
		private var roofType:int;
		private var upgrade:int;
		private var imgContainer:Sprite;
		
		public function BuildingItem(buildingIndex:int)
		{
			super();
			this.buildingIndex = buildingIndex;
			var me:Player = PlayerManager.getInstance().me;
			this.roofType = me.maxRoofType(buildingIndex);
			this.upgrade = me.maxUpgrade(buildingIndex);
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			//背景框
			var TabItemBackground:Class = ResourceHelper.getInstance().getClassByName("TabItemBackground");
			var tabItemBackground:Sprite = new TabItemBackground();
			addChild(tabItemBackground);
			//图片
			imgContainer = new Sprite();
			addChild(imgContainer);
			refreshImg();
			//标题名字
			var titleText:TextField = new TextField();
			titleText.selectable = false;
        	titleText.autoSize = TextFieldAutoSize.LEFT;
        	if (buildingConfig.name.length < 6)
        	{
        		titleText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x0088FF, true);
        	}
        	else
        	{
        		titleText.defaultTextFormat = new TextFormat("微软雅黑", 13, 0x0088FF, true);
        	}
			titleText.filters = [new GlowFilter(0xFFFFFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			titleText.text = buildingConfig.name;
			titleText.x = (tabItemBackground.width - titleText.width) / 2;
			titleText.y = 85;
			addChild(titleText);
			this.mouseChildren = false;
			addEventListener(MouseEvent.CLICK, onMouseClick);
			addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			//监听本人信息
			me.addEventListener(ModelEvent.REFRESH, onRefresh);
			//监听本人包裹信息
			me.packageModel.addEventListener(ModelEvent.REFRESH, onRefresh);
		}

		private function onMouseClick(event:MouseEvent):void
		{
			if (HomeScene.getInstance().getOperationMode() != HomeScene.NONEMODE)
				return;
			var popMessage:PopMessage;
			var me:Player = PlayerManager.getInstance().me;
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			if (HomeScene.getInstance().getCurrentTown().owner.userId != me.userId)
			{
				popMessage = new PopMessage("不能在别人的家里进行建设！", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else if (roofType < 0)
			{
				popMessage = new PopMessage("该建筑尚未开启！", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else if (buildingConfig.vitalityCost > me.vitality)
			{
				popMessage = new PopMessage("体力不足！", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else
			{ 
				var town:Town = HomeScene.getInstance().getCurrentTown();
				if (town.owner.townModel.getAvailablePoints(buildingIndex).length > 0)
				{
					var obj:Obj = new Obj();
					obj.objectIndex = ObjConfig.GOLDCOIN;
					obj.objectNum = -buildingConfig.priceGoldCoin;
					me.checkAndBuild(obj);
					me.addEventListener(ModelEvent.CHECK_AND_BUILD_COMPLETE, onCheckAndBuildComplete);
				}
				else
				{
					popMessage = new PopMessage("当前没有合适的地块建造！", 0xFF0000);
					WidgetManager.getInstance().popOut([popMessage]);
				}
			}
		}

		//设定处理信息的函数
		private function onCheckAndBuildComplete( event:ModelEvent ):void
		{
		 	var me:Player = PlayerManager.getInstance().me;
			me.removeEventListener(ModelEvent.CHECK_AND_BUILD_COMPLETE, onCheckAndBuildComplete);
		 	//接收到的是关于直接建造的信息返回
			var data:Object = event.data;
			if (data['err'] == 0)
			{
				var oldState:StateModel = new StateModel(me.userId);
				oldState.handleLoadStates(data['oldState']);
			 	SceneManager.getInstance().loadScene(BuildScene.getInstance());
			 	BuildScene.getInstance().changeParamByState(oldState);
			 	BuildScene.getInstance().startBuild(buildingIndex, me.maxHeight(buildingIndex), me.maxRoofType(buildingIndex));
			}
			else
			{
				var popMessage:PopMessage = new PopMessage("金币不足！", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
		}
		
		private function onMouseOver(event:MouseEvent):void
		{
			if (HomeScene.getInstance().getOperationMode() != HomeScene.NONEMODE)
				return;
			if (BottomPane.getInstance().extendFlag == BottomPane.STATUS_EXTEND)
			{
				if (roofType >= 0 && HomeScene.getInstance().getCurrentTown().owner.userId == PlayerManager.getInstance().myUserId)
				{ 
					var highlightColor:uint = false ? 0xFF0000 : 0x00FF00;
					var town:Town = HomeScene.getInstance().getCurrentTown();
					town.addHighLight(buildingIndex);
				}
				Mouse.cursor = "button";
				this.filters = [new ColorMatrixFilter(BFont.brightFilter)];
			
				//鼠标信息
				var globalPoint:Point = this.parent.localToGlobal(new Point(this.x, this.y));
				var buildingTip:BuildingMessage = new BuildingMessage(buildingIndex); 
				buildingTip.x = globalPoint.x - (buildingTip.width - width) / 2;
				buildingTip.y = globalPoint.y - buildingTip.height - 5;
				WidgetManager.getInstance().popOutMouseOverMessage(buildingTip);
			}
		}    
		
		private function onMouseOut(event:MouseEvent):void
		{
			Mouse.cursor = "auto";
			this.filters = null;
			WidgetManager.getInstance().closeMouseOverMessage();
			var town:Town = HomeScene.getInstance().getCurrentTown();
			town.removeHighLight();
		}

		public function onRefresh(event:ModelEvent):void
		{
			//判断是否解锁
			var me:Player = PlayerManager.getInstance().me;
			var currentRoofType:int = me.maxRoofType(buildingIndex);
			var currentUpgrade:int = me.maxUpgrade(buildingIndex);
			if (currentRoofType > roofType || currentUpgrade > upgrade)
			{
				//如果不是首次加载
				if (!(event.data != null && event.data.firstLoad))
				{
					//弹出解锁窗口
					var unlockBuildingMovie:UnlockBuildingMovie = new UnlockBuildingMovie(buildingIndex, currentRoofType, currentUpgrade, roofType, upgrade);
					WidgetManager.getInstance().popOutOneByOne(unlockBuildingMovie);
					//如果是首次解锁
					if (roofType == -1)
					{
						WidgetManager.getInstance().setPopOutOneByOneCallBack(startBuildingGuide, [buildingIndex]);
					}
				}
				roofType = currentRoofType;
				upgrade = currentUpgrade;
				refreshImg();
			} 
		}

		//开始新楼解锁后的引导
		private function startBuildingGuide(buildingIndex:int):void
		{
			//初始化引导列表（红楼）
			const guideMap:Object = {1: RedBuildingGuide};
			if (guideMap[buildingIndex] != null)
			{
				var buildingGuide:BuildingGuide = new guideMap[buildingIndex]();
				buildingGuide.step1();
				SceneManager.getInstance().topLayer.addChild(buildingGuide);
			}
		}
		
		private function refreshImg():void
		{
			while (imgContainer.numChildren > 0)
				imgContainer.removeChildAt(0);
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			var ObjectImage:Class;
			//是否加锁
			if (roofType < 0)
				ObjectImage = ResourceHelper.getInstance().getClassByName("QuestionBox");
			else
				ObjectImage = ResourceHelper.getInstance().getClassByName(buildingConfig.iconImage[roofType]);   
			var img:Sprite = new ObjectImage();
			img.x = (this.width - img.width) / 2;
			img.y = 88 - img.height;
			imgContainer.addChild(img);
			if (roofType >= 0 && upgrade > 0)
			{
				var UpgradeImage:Class = ResourceHelper.getInstance().getClassByName("Upgrade" + upgrade);
				var upgradeImage:Sprite = new UpgradeImage();
				upgradeImage.x = 60;
				upgradeImage.y = 10;
				imgContainer.addChild(upgradeImage);
			}
			//价格
			if (roofType >= 0)
			{
				var objectConfig:ObjConfig = Config.objConfigs[ObjConfig.GOLDCOIN];
				var goldcoinSprite:Sprite = getIconSprite(buildingConfig.priceGoldCoin, objectConfig.iconImage[0], 0xAAAA00);
				goldcoinSprite.x = 8;
				goldcoinSprite.y = 8;
				imgContainer.addChild(goldcoinSprite);
				var vitalitySprite:Sprite = getIconSprite(buildingConfig.vitalityCost, "VitalityIcon", 0x55AA00);
				vitalitySprite.x = 8;
				vitalitySprite.y = 28;
				imgContainer.addChild(vitalitySprite);
			}
			new Reflect({mc:img, alpha:50, ratio:80, distance:8, updateTime:-1, reflectionDropoff:1});
		}
		
		//获得图标和数字
		private function getIconSprite(number:int, imgClassName:String, color:uint):Sprite
		{
			var res:Sprite = new Sprite();
			//图标
			var ImgClass:Class = ResourceHelper.getInstance().getClassByName(imgClassName);
			var imgCoin:Sprite = new ImgClass();
			imgCoin.height = 20;
			imgCoin.scaleX = imgCoin.scaleY;
			res.addChild(imgCoin);
			//数值
			var numberText:TextField = new TextField();
			numberText.selectable = false;
        	numberText.autoSize = TextFieldAutoSize.LEFT;
    		numberText.defaultTextFormat = new TextFormat("微软雅黑", 12, color, true);
			numberText.filters = [new GlowFilter(0xFFFFFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			numberText.text = BFont.formatNumWithComa(number);
			numberText.x = 22;
			numberText.y = 0;
			res.addChild(numberText);
			return res;
		}
		
	}
}